import React, { useState } from 'react';
import styles from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/index.less';
import { Icon, Upload, message, Modal } from 'antd';
import { formatMessage } from 'umi';
import cookie from 'js-cookie';
import xss from 'xss';
import { download } from '@/utils/utils';

const { Dragger } = Upload;

const ExcelUploader = ({
    showImportDialog,
    uploadAction,
    dispatchType,
    dispatch,
    showTemplateButton,
    extra,
    extraParams
}) => {
    const { showImportDialogType, searchType, downloadTemplateType } = dispatchType;

    const [fileList, setFileList] = useState([]);
    /**
     * 关闭弹框
     */
    const closeImportDialog = () => {
        dispatch({
            type: showImportDialogType,
            payload: false
        });
    };

    const uploadProps = {
        name: 'file',
        multiple: false,
        accept: '.xls,.xlsx',
        action: `${uploadAction}${extraParams()}`,
        headers: {
            Authorization: cookie.get('Authorization')
        },
        showUploadList: true,
        fileList,
        beforeUpload(file, fileArray) {
            if (fileArray.length > 1) {
                // 只能上传一个文件
                message.warn(formatMessage({ id: 'importExcel.onlyOneFile' }));
                setFileList([]);
                return false;
            }
            return true;
        },
        onChange({ file, fileList: fileArray /* , event */ }) {
            if (file.status !== 'done') {
                setFileList([...fileArray]);
                return;
            }
            // 上传完成
            const { code } = file.response;

            if (code === 10000) {
                // 将上传的文件列表清空
                fileArray.splice(0);
                message.success(formatMessage({ id: 'importExcel.importSuccess' }));
                closeImportDialog();
                dispatch({ type: searchType });
                setFileList([]);
                return;
            }

            Modal.error({
                // 导入失败
                title: formatMessage({ id: 'importExcel.importFail' }),
                // 知道了
                okText: formatMessage({ id: 'importExcel.alreadyKnow' }),
                content: (
                    <div
                        style={{ overflow: 'auto', maxHeight: 300, paddingRight: 15 }}
                        dangerouslySetInnerHTML={{ __html: xss(file.response.msg) }}
                    />
                )
            });
            setFileList([]);
        }
    };

    const downloadTemplate = () => {
        download({
            getData: () => dispatch({ type: downloadTemplateType })
        });
    };

    return (
        <div className={`${styles.mask} ${showImportDialog ? styles.active : ''}`}>
            <Icon type="close" onClick={closeImportDialog} className={styles.close} />
            <div className={styles.dragBox}>
                {extra}
                <Dragger {...uploadProps}>
                    <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                    </p>
                    <p className="ant-upload-text">
                        {/* 点击或将Excel文件拖拽到这里导入 */}
                        {formatMessage({ id: 'importExcel.dragInfo' })}
                    </p>
                </Dragger>
                <div className={styles.downloadTemplateBox}>
                    {showTemplateButton ? (
                        <a onClick={downloadTemplate}>
                            {/* 点击下载Excel模板 */}
                            {formatMessage({ id: 'importExcel.downloadTemplate' })}
                        </a>
                    ) : (
                        ''
                    )}
                </div>
            </div>
        </div>
    );
};

ExcelUploader.defaultProps = {
    extra: null,
    extraParams: () => ('')
};

export default ExcelUploader;
